package com.medata.controller;

import com.google.gson.*;
import com.medata.dataObject.*;
import com.medata.exeptions.YunExceptions;
import com.medata.service.DatabaselistService;
import com.medata.service.GlobalsettingService;
import com.medata.service.LogMakeDocumentService;
import com.medata.service.ResserverService;
import com.medata.service.impl.*;
import com.medata.utils.*;
import com.medata.vo.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.hibernate.engine.spi.SessionImplementor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ：zb
 * @date ：Created in 2019/5/6 0006 9:32
 * @description：
 */
@Controller
@RequestMapping("/editor")
@Api
@Slf4j
public class EditorController {
    @Value("${perfix}")
    private String perfix;
    @Autowired
    private DatabaselistService databaselistService;
    @Autowired
    private GlobalsettingService globalsettingService;
    @Autowired
    private LogMakeDocumentService logMakeDocumentService;
    @Autowired
    private AccountServiceImpl accountService;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private DocobjectServiceImpl docobjectService;
    @Autowired
    private ResserverService resserverService;
    @Value("${ServerIP}")
    private String ip;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private TemplatefieldsServiceImpl templatefieldsService;
    @Autowired
    private DefaultValueTableServiceImpl defaultValueTableService;

    //获取导入表单2-->20190626优化通用版
    @RequestMapping(value = "/zlpost/{dbid}/{str}", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView getZlList2(@PathVariable Integer dbid, @PathVariable String str){
        ModelAndView mv=new ModelAndView();
        List<Templatefields> templatefields = templatefieldsService.getByDbidOrderBySequence(dbid);
        List<FieldsVO> fieldsVOS=new ArrayList<>();
        for (Templatefields templatefield:templatefields){
            if (templatefield.getInputType()==0){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType("0");
                fieldsVO.setIsneed(templatefield.getIsNeed());
                fieldsVO.setKey(templatefield.getTpFieldName());
                fieldsVOS.add(fieldsVO);
            }
            if (templatefield.getInputType()==2){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType("2");
                fieldsVO.setIsneed(templatefield.getIsNeed());
                fieldsVO.setKey(templatefield.getTpFieldName());
                List<String> values=new ArrayList<>();
                List<DefaultValueTable> tables = defaultValueTableService.findByRefId(templatefield.getRefId());
                for (DefaultValueTable table:tables){
                    values.add(table.getDefValues());
                }
                fieldsVO.setValuelist(values);
                fieldsVOS.add(fieldsVO);
            }
        }
        String[] split = str.split("@");
        if (split.length == 2) {
            mv.addObject("ss", split[0]);
            mv.addObject("page", split[1]);
        } else {
            mv.addObject("page", split[0]);
        }
        mv.addObject("fieldsVOS",fieldsVOS);
        mv.setViewName("zlform");
        Databaselist databaselist = databaselistService.findByDbid(dbid);
        mv.addObject("dc", databaselist.getDbtitle());
        mv.addObject("dbid", dbid);
        return mv;

    }

    //导入数据库信息2
    @RequestMapping(value = "/zlpost", method = RequestMethod.POST)
    @ResponseBody
    public void zlpost(HttpServletResponse response,MultipartFile[] file,String Field,String dbid,String docid,Integer isgys,String fj){
        Resserver resserver = resserverService.findByServerport("6896");
        String filePath=resserver.getRespath();
        int isUpdate=0;
        if (docid!=null){
            isUpdate=1;
        }
        Field=XmlUtil.getReplace(Field);
        //获取连接
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        //获取redis数据
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String tempJson = ops.get(String.valueOf(dbid));
        Gson gson = new Gson();
        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(tempJson).getAsJsonArray();
        List<Templatefields> templatefieldsList = new ArrayList<>();
//        for (JsonElement temp : jsonArray) {
//            Templatefields templatefields = gson.fromJson(temp, Templatefields.class);
//            templatefieldsList.add(templatefields);
//        }
        templatefieldsList=templatefieldsService.getByDbid(Integer.valueOf(dbid));
        templatefieldsList=templatefieldsList.stream().sorted((p1,p2)->(Integer.valueOf(p1.getSequence())-Integer.valueOf(p2.getSequence()))).collect(Collectors.toList());
        //解析成xml
        StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"utf-8\"?><DispFields>");
        String[] fields = Field.split("@");
        String doctitles = fields[0];
        String[] titles = doctitles.split(":");
        String title = titles[1];
        title=title.replaceAll(",","");
        StringBuffer xmlfields = TempfieldToXmlUtil.getXml2(defaultValueTableService,title,templatefieldsList,fields);
        xml.append(xmlfields).append("</DispFields>");

        //验重
        String dbaName=null;
        Templatefields tp = templatefieldsList.get(0);
        Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(dbid));
        dbaName=databaselist.getDbname();

        //封装成数据集
        String name = (String) SecurityUtils.getSubject().getPrincipal();
        Account account = accountService.findByUserName(name);
        ZlPostVo zlVo=new ZlPostVo();
        zlVo.setDoccontent(xml.toString());
        if (docid!=null){
            zlVo.setDocid(docid);
        }
        zlVo.setDocauthor(name);
        zlVo.setDbid(Integer.valueOf(dbid));
        zlVo.setUserid(account.getUserId());
        zlVo.setDoctitle(title);
        Timestamp createDate = Timestamp.valueOf(TimeUtil.getCurDate());
        zlVo.setCreatedate(createDate);
        String objectTitle = null;
        int hasFile = 0;
        for (MultipartFile file1 : file) {
            if (!file1.getOriginalFilename().equals("")) {
                hasFile = 1;
            }
            if (file1.getOriginalFilename() != null && !file1.getOriginalFilename().isEmpty()) {
                if (!(file1.getOriginalFilename().endsWith(".pdf") || file1.getOriginalFilename().endsWith(".jpg"))) {
                    try {
                        response.setHeader("Content-type", "text/html;charset=UTF-8");
                        PrintWriter writer = response.getWriter();
                        writer.print("<script type='text/javascript'>alert('上传资料的格式超出指定类型');history.go(-1)</script>");
                        writer.flush();
                        writer.close();
                        return;
                    } catch (Exception e) {
                        throw new YunExceptions(0, "上传资料的时候文件格式超出指定类型");
                    }
                }
            }
        }

        zlVo.setHasobject(String.valueOf(hasFile));
        String sql = "insert into " + dbaName + "(DocTitle,DocContent,DocAuthor,DBID,UserID,CreateDate,hasobject,HitCount,isCheck)"
                + "values ( '" + zlVo.getDoctitle() + "','" + zlVo.getDoccontent() + "','" + zlVo.getDocauthor() + "','" + zlVo.getDbid() + "','" + zlVo.getUserid() + "','" + zlVo.getCreatedate() + "'," + zlVo.getHasobject() + "," + " '0'" + "," + "'"+zlVo.getIscheck()+"'" + ")";
        String sql2 = null;
        if (hasFile == 1) {
            sql2 = "update " + dbaName + " set DocTitle= '" + zlVo.getDoctitle() + "', DocContent= '" + zlVo.getDoccontent()
                    + "', DocAuthor= '" + zlVo.getDocauthor() + "', DBID='" + zlVo.getDbid() + "', UserID='" + zlVo.getUserid() + "', CreateDate='" + zlVo.getCreatedate() + "', hasobject='" + zlVo.getHasobject() + "' where docid='" + docid + "'";
        } else {
            sql2 = "update " + dbaName + " set DocTitle= '" + zlVo.getDoctitle() + "', DocContent= '" + zlVo.getDoccontent()
                    + "', DocAuthor= '" + zlVo.getDocauthor() + "', DBID='" + zlVo.getDbid() + "', UserID='" + zlVo.getUserid() + "', CreateDate='" + zlVo.getCreatedate() + "' where docid='" + docid + "'";

        }

        if (docid==null){
            try {
                PreparedStatement ps = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                ps.execute();
                ResultSet rs = ps.getGeneratedKeys();
                while(rs.next()){
                    docid=rs.getString(1);
                }
                SolrUtils.insertIndexs(globalsettingService,Integer.valueOf(dbid),dbaName,0, docid);
            }catch (Exception e){
                e.printStackTrace();
                throw  new YunExceptions(0,"保存数据出现bug");
            }
        }else {
            try {
                isUpdate=1;
                PreparedStatement ps = connection.prepareStatement(sql2);
                ps.execute();
                SolrUtils.updateIndex(globalsettingService,Integer.valueOf(dbid),dbaName,0,docid);
            }catch (Exception e){
                e.printStackTrace();
                throw new YunExceptions(0,"保存数据出现bug");
            }
        }
        for (MultipartFile file1 : file) {
            if (hasFile == 1) {
                Docobject docobject = new Docobject();
                File faPath = new File(filePath);
                if (!faPath.exists()) {
                    faPath.mkdir();
                }
                String filename =file1.getOriginalFilename();
                if (filename != null && !filename.isEmpty()) {
                    objectTitle = objectTitle == null ?zlVo.getDoctitle() + "_"  + "_" + filename : objectTitle + "@@" + zlVo.getDoctitle() + "_"  + "_" + filename;
                    //20190613更新
                    String ServerFullPath = "/"+docid+"/"+ filename;
                    String filepathWay=filePath+"/"+dbaName+"/"+"/"+docid+"/";
                    String filepath2=filePath+"/"+dbaName+"/"+"/"+docid+"/"+ filename;
                    File file2Way=new File(filepathWay);
                    File file2 = new File(filepath2);
                    try {
                        if (!file2Way.exists()){
                            file2Way.mkdirs();
                        }
                        file1.transferTo(file2);
                        docobject.setDbid(dbid);
                        //20190612更新
//                        docobject.setClientfullpath(dbaName);
                        docobject.setDocid(String.valueOf(docid));
                        docobject.setObjectfilename(filename);
                        docobject.setCreatetime(createDate);
                        docobject.setPublishflag("1");
                        docobject.setUploadflag("1");
                        docobject.setServerfullpath(ServerFullPath);
                        docobject.setObjectsize(String.valueOf(file1.getSize()));
                        docobjectService.saveOrUpdate(docobject);
                        //将首尾页生成压缩pdf文件
                    } catch (Exception e) {
                        throw new YunExceptions(1, "文件上传失败");
                    }
                }
            }
        }
        try {
            LogMakeDocument logMakeDocument = new LogMakeDocument();
            logMakeDocument.setActionid(100);
            logMakeDocument.setUserId(zlVo.getUserid());
            logMakeDocument.setDocid(Integer.valueOf(docid));
            logMakeDocument.setDocTitle(databaselist.getDbtitle() + "_" + zlVo.getDoctitle());
            logMakeDocument.setLogtime(Timestamp.valueOf(TimeUtil.getCurDate()));
            logMakeDocument.setUserName(zlVo.getDocauthor());
            logMakeDocument.setObjectTitle(objectTitle);
            logMakeDocumentService.saveOrUpdate(logMakeDocument);
            if (hasFile==1){
                LogMakeDocument logMakeDocument1 = new LogMakeDocument();
                logMakeDocument1.setActionid(101);
                logMakeDocument1.setUserId(zlVo.getUserid());
                logMakeDocument1.setDocid(Integer.valueOf(docid));
                logMakeDocument1.setDocTitle(databaselist.getDbtitle() + "_" + zlVo.getDoctitle());
                logMakeDocument1.setLogtime(Timestamp.valueOf(TimeUtil.getCurDate()));
                logMakeDocument1.setUserName(zlVo.getDocauthor());
                logMakeDocument1.setObjectTitle(objectTitle);
                logMakeDocumentService.saveOrUpdate(logMakeDocument1);
            }
        } catch (Exception e) {
            throw new YunExceptions(0, "元数据操作记录存数据库时发生错误");
        }
        try {
            PrintWriter writer = response.getWriter();
            writer.print("<script type='text/javascript'>alert('提交成功');history.go(-2);self.parent.$('#checkChange').val('1')</script>");
            writer.flush();
            writer.close();
        }catch (Exception e){
            e.printStackTrace();
            throw new YunExceptions(0,"导入数据的时候出现bug");
        }
        return;
    }


    //将文件打包成zip,并下载-->没用上
    @RequestMapping(value = "/fileGet", method = RequestMethod.POST)
    public HttpServletResponse getFile(HttpServletResponse response, String docid, String dba) {
        List<Docobject> docobjectList = docobjectService.findByDocidAndClientfullpath(docid, dba);
        List<String> files = new ArrayList<>();
        for (Docobject docobject : docobjectList) {
            String file = docobject.getServerfullpath();
            files.add(file);
        }
        String zipFile = null;
        try {
            zipFile = FileUploadUtil.compressFiles(files, "c:/test/" + TimeUtil.getCurDay() + "/" + UidUtil.getUid() + ".zip");
        } catch (Exception e) {
            try {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.print("<script type='text/javascript'>alert('文件资源异常,请联系管理员');history.go(-1)</script>");
                writer.flush();
                writer.close();
                return null;
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        response = FileUploadUtil.download(new File(zipFile), response);
        return null;
    }

    //获取修改资料
    @RequestMapping(value = "/zlupdate/{dbid}/{docid}/{str}", method = RequestMethod.GET)
    public ModelAndView test(@PathVariable Integer dbid, @PathVariable String docid, @PathVariable String str) {
        ModelAndView mv=new ModelAndView();
        Integer hasAuthority = AuthorityUtil.hasAuthority(accountService, String.valueOf(dbid));
        if (hasAuthority == 0) {
            throw new UnauthorizedException();
        }
        String title=null;
        //增加资料信息
        Databaselist databaselist = databaselistService.findByDbid(dbid);
        String sql = "SELECT * from " + databaselist.getDbname() + " where docid=" + docid;
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        String xml = null;
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                title=rs.getString(2);
                xml = rs.getString(3);
            }
        } catch (Exception e) {
            throw new YunExceptions(0, "修改客户资料时,数据库获取信息异常");
        }
        Map<String,String> valueMap = XmlUtil.getValues(xml, Integer.valueOf(dbid), 100);

        //是否已经录入供应商名单
        if (dbid==16){
            DefaultValueTable vTable = defaultValueTableService.findByDefValuesAndRefId(title, 102);
            if (vTable==null){
                mv.addObject("hasInput","0");
            }else {
                mv.addObject("hasInput","1");
            }
        }else{
            mv.addObject("hasInput","0");
        }
        List<Templatefields> templatefields = templatefieldsService.getByDbidOrderBySequence(dbid);
        List<FieldsVO> fieldsVOS=new ArrayList<>();
        for (Templatefields templatefield:templatefields){
            if (templatefield.getInputType()==0){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType("0");
                fieldsVO.setIsneed(templatefield.getIsNeed());
                fieldsVO.setKey(templatefield.getTpFieldName());
                //添加数据信息
                String fieldDesc = templatefield.getTpFieldDesc();
                String value = DataUtil.getValue(fieldDesc, valueMap);
                value=XmlUtil.getUnreplace(value);
                fieldsVO.setValue(value);
                fieldsVOS.add(fieldsVO);
            }
            //文本框
            if (templatefield.getInputType()==8){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType("8");
                fieldsVO.setIsneed(templatefield.getIsNeed());
                fieldsVO.setKey(templatefield.getTpFieldName());
                //添加数据信息
                String fieldDesc = templatefield.getTpFieldDesc();
                String value = DataUtil.getValue(fieldDesc, valueMap);
                value=XmlUtil.getUnreplace(value);
                fieldsVO.setValue(value);
                fieldsVOS.add(fieldsVO);
            }
            if (templatefield.getInputType()==2){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType("2");
                fieldsVO.setIsneed(templatefield.getIsNeed());
                fieldsVO.setKey(templatefield.getTpFieldName());
                List<String> values=new ArrayList<>();
                List<DefaultValueTable> tables = defaultValueTableService.findByRefId(templatefield.getRefId());
                for (DefaultValueTable table:tables){
                    values.add(table.getDefValues());
                }
                fieldsVO.setValuelist(values);
                //添加数据信息
                String fieldDesc = templatefield.getTpFieldDesc();
                String value = DataUtil.getValue(fieldDesc, valueMap);
                fieldsVO.setValue(value);

                fieldsVOS.add(fieldsVO);
            }
            if (templatefield.getInputType()==4|templatefield.getInputType()==7){
                FieldsVO fieldsVO=new FieldsVO();
                fieldsVO.setDesc(templatefield.getTpFieldDesc());
                fieldsVO.setInputType(String.valueOf(templatefield.getInputType()));
                fieldsVO.setKey(templatefield.getTpFieldName());
                fieldsVO.setIsneed(templatefield.getIsNeed());
                //添加数据信息
                if (templatefield.getInputType()==4){
                    String fieldDesc = templatefield.getTpFieldDesc();
                    String value = DataUtil.getValue(fieldDesc, valueMap);
                    fieldsVO.setValue(value);
                }else{
                    String fieldDesc = templatefield.getTpFieldDesc();
                    String value = DataUtil.getValue(fieldDesc, valueMap);
                    String[] values = value.split(",");
                    List<String> list = Arrays.asList(values);
                    fieldsVO.setValues(list);
                }
                fieldsVOS.add(fieldsVO);
            }
        }
        String[] split = str.split("@");
        if (split.length == 2) {
            mv.addObject("ss", split[0]);
            mv.addObject("page", split[1]);
        } else {
            mv.addObject("page", split[0]);
        }
        mv.addObject("fieldsVOS",fieldsVOS);
        mv.setViewName("zlUpdateForm");
        mv.addObject("dc", databaselist.getDbtitle());
        mv.addObject("dbid", dbid);
        //添加文件信息
        List<Docobject> docLists = docobjectService.findByDocidAndDbid(docid, String.valueOf(dbid));
        mv.addObject("docLists", docLists);
        return mv;
    }

    //删除文件
    @RequestMapping(value = "/fileDelete/{objID}", method = RequestMethod.GET)
    public void fileDelete(@PathVariable String objID, HttpServletResponse response) {
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        Resserver resserver = resserverService.findByServerport("6896");
        String filePath=resserver.getRespath();
        try {
            Docobject docobject = docobjectService.findAllByObjectid(objID);
            String docid = docobject.getDocid();
            Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(docobject.getDbid()));
            String dba=databaselist.getDbname();
            String dbid = docobject.getDbid();
            String serverfullpath = docobject.getServerfullpath();
            String oldFilePath=filePath+"/"+dba+"/"+serverfullpath;
            File oldFile = new File(oldFilePath);
            FileUtils.deleteQuietly(oldFile);

            //记录删除记录
            String username = (String) SecurityUtils.getSubject().getPrincipal();
            LogMakeDocument logMakeDocument = new LogMakeDocument();
            logMakeDocument.setActionid(103);
            logMakeDocument.setUserId(accountService.findByUserName(username).getUserId());
            logMakeDocument.setDocid(Integer.valueOf(docobject.getDocid()));
            //获取doctitle
            String sql = "select * from " + dba + " where DocID= " + "'" + docid + "'";
            PreparedStatement ps1 = connection.prepareStatement(sql);
            ResultSet rs = ps1.executeQuery();
            while(rs.next()){
                String doctitle = rs.getString(2);
                logMakeDocument.setDocTitle(databaselist.getDbtitle()+"_"+doctitle);
            }
            logMakeDocument.setLogtime(Timestamp.valueOf(TimeUtil.getCurDate()));
            logMakeDocument.setUserName(username);
            logMakeDocument.setObjectTitle(docobject.getObjectfilename());
            logMakeDocumentService.saveOrUpdate(logMakeDocument);
            //

            docobjectService.deleteByObjectid(objID);
            List<Docobject> docobjectList = docobjectService.findByDocidAndClientfullpath(docid, dba);
            if (docobjectList == null || docobjectList.size() == 0) {
                String sql2 = "update " + dba + " set hasobject= 0 where DocID= " + "'" + docid + "'";
                PreparedStatement ps = connection.prepareStatement(sql2);
                ps.execute();
                SolrUtils.updateIndex(globalsettingService, Integer.valueOf(dbid), dba, 0, docid);
            }
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.print("<script type='text/javascript'>alert('删除成功');window.location.href=</script>");
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new YunExceptions(0, "删除文件资料时出现异常");
        }

    }

    //删除资料
    @RequestMapping(value = "/zldelete", method = RequestMethod.POST)
    @ResponseBody
    public void zlDelete(String str, String sp) {
        Resserver resserver = resserverService.findByServerport("6896");
        String filePath=resserver.getRespath();
        try {
            SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
            Connection connection = session.connection();
            String[] splits = str.split(sp);
            String[] dbids = sp.split("/editor/zlupdate/");
            String dbid = dbids[1];
            dbid = dbid.replaceAll("\\/", "");
            Integer hasAuthority = AuthorityUtil.hasAuthority(accountService, dbid);
            if (hasAuthority == 0) {
                throw new UnauthorizedException();
            }
            Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(dbid));
            for (String s : splits) {
                if (s != null && !s.isEmpty()) {
                    String sql2 = "select * from " + databaselist.getDbname() + " where docid='" + s + "'";
                    String sql = "delete from " + databaselist.getDbname() + " where docid='" + s + "'";
                    PreparedStatement ps2 = connection.prepareStatement(sql2);
                    ResultSet rs2 = ps2.executeQuery();
                    String docTitle = null;
                    String docid=null;
                    while (rs2.next()) {
                        docid=rs2.getString(1);
                        docTitle = rs2.getString(2);
                    }
                    //删除defaulttable关联记录
                    List<Templatefields> templatefields = templatefieldsService.getByDbid(Integer.valueOf(dbid));
                    Templatefields templatefields1 = templatefields.get(0);
                    if (templatefields1.getRefId()!=0&&templatefields1.getInputType()==0){
                        Integer refId = templatefields1.getRefId();
                        DefaultValueTable table = defaultValueTableService.findByDefValuesAndRefId(docTitle, refId);
                        if (dbid.equals("16")){
                            String sql3="select * from gyszl where doctitle = '"+docTitle+"'";
                            PreparedStatement ps3 = connection.prepareStatement(sql3);
                            ResultSet rs = ps3.executeQuery();
                            if (!rs.next()){
                                DefaultValueTable table1 = defaultValueTableService.findByDefValuesAndRefId(docTitle, 102);
                                if (table1!=null){
                                    defaultValueTableService.delete(table1);
                                }
                            }
                        }
                        if (table!=null){
                            defaultValueTableService.delete(table);
                        }
                    }

                    PreparedStatement ps = connection.prepareStatement(sql);
                    ps.execute();
                    List<Docobject> docobjects = docobjectService.findByDocidAndDbid(s, dbid);
                    String objectTitle = null;
                    for (Docobject d : docobjects) {
                        String serverfullpath = d.getServerfullpath();
                        String oldFilePath=filePath+"/"+databaselist.getDbname()+"/"+serverfullpath;
                        File oldFile = new File(oldFilePath);
                        FileUtils.deleteQuietly(oldFile);
                        docobjectService.deleteByObjectid(d.getObjectid());
                        objectTitle = (objectTitle == null) ? d.getObjectfilename() : objectTitle + "@@" + d.getObjectfilename();
                    }
                    SolrUtils.deleteIndex(globalsettingService, databaselist.getDbname(), s);
                    try {
                        String name = (String) SecurityUtils.getSubject().getPrincipal();
                        Account account = accountService.findByUserName(name);
                        LogMakeDocument logMakeDocument = new LogMakeDocument();
                        logMakeDocument.setActionid(102);
                        logMakeDocument.setUserId(account.getUserId());
                        logMakeDocument.setDocid(Integer.valueOf(s));
                        logMakeDocument.setDocTitle(databaselist.getDbtitle() + "_" + docTitle);
                        logMakeDocument.setLogtime(Timestamp.valueOf(TimeUtil.getCurDate()));
                        logMakeDocument.setUserName(name);
                        logMakeDocument.setObjectTitle(objectTitle);
                        logMakeDocumentService.saveOrUpdate(logMakeDocument);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new YunExceptions(0, "元数据操作记录删除数据库时发生错误");
                    }
                }
            }
        } catch (Exception e) {
            log.info("资料删除失败");
            e.printStackTrace();
            throw new YunExceptions(0, "资料删除失败");
        }
        return;
    }

    //单文件下载
    @RequestMapping(value = "fileDown/{objId}")
    public void fileDwon(HttpServletResponse response, @PathVariable String objId) {
        Resserver resserver = resserverService.findByServerport("6896");
        String filePath=resserver.getRespath();
        try {
            Docobject objectid = docobjectService.findAllByObjectid(objId);
            String path = objectid.getServerfullpath();
            Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(objectid.getDbid()));
            String dbaname=databaselist.getDbname();
            File file = new File(filePath+"/"+dbaname+"/"+path);
            String tempPath = filePath + "/tempFiles/"+dbaname+"/" +UidUtil.getUid()+"/"+ objectid.getObjectfilename();
            File tempfile = new File(tempPath);
            FileUtils.copyFile(file, tempfile);
            String filename = objectid.getObjectfilename();
            response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));
            FileCopyUtils.copy(new FileInputStream(tempfile), response.getOutputStream());
        } catch (Exception e) {
            try {
                response.setHeader("Content-type", "text/html;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.print("<script type='text/javascript'>alert('文件资源异常,请联系管理员');history.go(-1)</script>");
                writer.flush();
                writer.close();
            } catch (Exception e1) {
                throw new YunExceptions(0, "下载单个文件的时候,资源异常");
            }
        }
        return;
    }

    //获取solr库所有资料
    @RequestMapping(value = "solrSearch/{dbid}/{page}", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView get_solr_all(@PathVariable String dbid, @PathVariable String page) {
        Gson gson = new Gson();
        ZlTableVo2 zlTableVo2 = new ZlTableVo2();
        Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(dbid));
        ModelAndView mv = new ModelAndView();
        //是否有获取资料权限
        Integer hasAuthority = AuthorityUtil.hasAuthority(accountService, String.valueOf(dbid));
        if (hasAuthority == 0) {
            throw new UnauthorizedException();
        }
        //查询suoyinku
        String headXml = SolrXmlUtil.headXml(dbid);
        String returnXml = SolrXmlUtil.returnXml(templatefieldsService, dbid);
        String searchXml = SolrXmlUtil.searchXml(templatefieldsService, Integer.valueOf(dbid), null, null, page);
        String xml = headXml + returnXml + searchXml;
        JsonObject jsonObject = SolrCrudUtil.simp_search(globalsettingService, xml);
        String total = jsonObject.get("total").getAsString();
        int pagesize = 10;
        int pageCount = Integer.valueOf(total) % pagesize == 0 ? Integer.valueOf(total) / pagesize : (Integer.valueOf(total) / pagesize + 1);
        int diffValue = pageCount - Integer.valueOf(page);
        JsonArray docs = jsonObject.get("docs").getAsJsonArray();
        LinkedList<String> colums = new LinkedList<>();
        LinkedList<LinkedList<String>> values = new LinkedList<>();
        int hascolumn = 0;
        //获取redis数据-->验证到期
        int checkExpire=0;
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String tempJson = ops.get(String.valueOf(dbid));
        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(tempJson).getAsJsonArray();
        List<String> expiredList=new ArrayList<>();
        int errors=0;
        for (JsonElement temp : jsonArray) {
            Templatefields templatefields = gson.fromJson(temp, Templatefields.class);
        }
        int datalist=checkExpire==1?4:5;

        for (JsonElement element : docs) {
            SolrReturnBean returnBean = gson.fromJson(element, SolrReturnBean.class);
            LinkedList<String> value = new LinkedList<>();
            LinkedList<SolrReturnBean_Son> fieldlist = returnBean.getField();
            value.add(returnBean.getId());
            for (int x = 0; x < datalist; x++) {
                SolrReturnBean_Son field = fieldlist.get(x);
                //20190910
                value.add(XmlUtil.getUnreplace(field.getFieldvalue()));
                if (hascolumn == 0) {
                    colums.add(field.getFielddesc());
                }
            }
            StringBuffer expiredField=new StringBuffer("");
            int iserror=0;
            if (checkExpire==1){
                for (SolrReturnBean_Son son:fieldlist){
                    if (expiredList.contains(son.getFielddesc())){
                        String timeValue = son.getFieldvalue();
                        if (timeValue!=null&&!timeValue.isEmpty()){
                            String[] split = timeValue.split("-");
                            if (split[1].length()<2){
                                timeValue=split[0]+"0"+split[1]+split[2];
                            }else {
                                timeValue=split[0]+split[1]+split[2];
                            }
                            Integer expiredTime=Integer.valueOf(timeValue);
                            Integer curTime = Integer.valueOf(TimeUtil.getCurDay());
                            if (curTime>expiredTime){
                                expiredField.append(son.getFielddesc()+"到期,");
                                iserror=1;
                            }
                        }else {
                                expiredField.append(son.getFielddesc()+"未录入,");
                                iserror=1;
                        }
                    }
                }
                if (expiredField.length()<1){
                    value.add("资料有效期内");
                }else {
                    value.add(expiredField.toString());
                }
            }
            if (iserror==1){
                errors++;
            }
            hascolumn = 1;
            for (SolrReturnBean_Son son : fieldlist) {
                if (son.getFieldname().equalsIgnoreCase("createDate")) {
                    String timeValue = son.getFieldvalue();
                    if (timeValue != null && !timeValue.isEmpty()) {
                        timeValue = TimeUtil.getD8Date(timeValue);
                    }
                    value.add(timeValue);
                }
            }
            value.add(fieldlist.get(fieldlist.size() - 1).getFieldvalue());
            values.add(value);

        }

        if (checkExpire==1){
            colums.add("信息情况");
        }
        colums.add("更新时间");
        colums.add("已上传文件");
        zlTableVo2.setColums(colums);
        zlTableVo2.setValuelist(values);
        List<String> searchFields = SearchFieldUtils.getfield(redisTemplate, dbid);
        mv.addObject("errors",errors+"/"+total);
        mv.addObject("searchList", searchFields);
        mv.addObject("page", Integer.valueOf(page));
        mv.addObject("ZlVo", zlTableVo2);
        mv.addObject("dbid", dbid);
        mv.addObject("dc", databaselist.getDbtitle());
        mv.addObject("dba", databaselist.getDbname());
        mv.addObject("diffValue", diffValue);
        mv.addObject("prePage", Integer.valueOf(page) - 1);
        mv.addObject("pageCount", pageCount);
        mv.addObject("count", total);
        mv.addObject("pageSize", pagesize);
        mv.addObject("perfix",perfix);
        mv.setViewName("solrTable");
        return mv;
    }

    //获取solr搜索结果
    @RequestMapping(value = "solrSearch/{dbid}/{word}/{str}/{page}", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView getObjects(@PathVariable String dbid, @PathVariable String word, @PathVariable String str, @PathVariable String page) {
        Gson gson = new Gson();
        ZlTableVo2 zlTableVo2 = new ZlTableVo2();
        Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(dbid));
        ModelAndView mv = new ModelAndView();
        //是否有获取资料权限
        Integer hasAuthority = AuthorityUtil.hasAuthority(accountService, String.valueOf(dbid));
        if (hasAuthority == 0) {
            throw new UnauthorizedException();
        }
        //查询suoyinku
        String headXml = SolrXmlUtil.headXml(dbid);
        String returnXml = SolrXmlUtil.returnXml(templatefieldsService, dbid);
        String searchXml = SolrXmlUtil.searchXml(templatefieldsService, Integer.valueOf(dbid), word, str, page);
        String xml = headXml + returnXml + searchXml;
        JsonObject jsonObject = SolrCrudUtil.simp_search(globalsettingService, xml);
        String total = jsonObject.get("total").getAsString();
        int pagesize = 10;
        int pageCount = Integer.valueOf(total) % pagesize == 0 ? Integer.valueOf(total) / pagesize : (Integer.valueOf(total) / pagesize + 1);
        int diffValue = pageCount - Integer.valueOf(page);
        JsonArray docs = jsonObject.get("docs").getAsJsonArray();
        LinkedList<String> colums = new LinkedList<>();
        LinkedList<LinkedList<String>> values = new LinkedList<>();
        int hascolumn = 0;

        //获取redis数据-->验证到期
        int checkExpire=0;
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String tempJson = ops.get(String.valueOf(dbid));
        JsonParser parser = new JsonParser();
        JsonArray jsonArray = parser.parse(tempJson).getAsJsonArray();
        List<String> expiredList=new ArrayList<>();
        int errors=0;
        for (JsonElement temp : jsonArray) {
            Templatefields templatefields = gson.fromJson(temp, Templatefields.class);
        }
        int datalist=checkExpire==1?4:5;

        for (JsonElement element : docs) {
            SolrReturnBean returnBean = gson.fromJson(element, SolrReturnBean.class);
            LinkedList<String> value = new LinkedList<>();
            LinkedList<SolrReturnBean_Son> fieldlist = returnBean.getField();
            value.add(returnBean.getId());
            for (int x = 0; x < datalist; x++) {
                SolrReturnBean_Son field = fieldlist.get(x);
                //20190910修正显示特殊字符
                value.add(XmlUtil.getUnreplace(field.getFieldvalue()));
                if (hascolumn == 0) {
                    colums.add(field.getFielddesc());
                }
            }
            StringBuffer expiredField=new StringBuffer("");
            int iserror=0;
            if (checkExpire==1){
                for (SolrReturnBean_Son son:fieldlist){
                    if (expiredList.contains(son.getFielddesc())){
                        String timeValue = son.getFieldvalue();
                        if (timeValue!=null&&!timeValue.isEmpty()){
                            String[] split = timeValue.split("-");
                            if (split[1].length()<2){
                                timeValue=split[0]+"0"+split[1]+split[2];
                            }else {
                                timeValue=split[0]+split[1]+split[2];
                            }
                            Integer expiredTime=Integer.valueOf(timeValue);
                            Integer curTime = Integer.valueOf(TimeUtil.getCurDay());
                            if (curTime>expiredTime){
                                expiredField.append(son.getFielddesc()+"到期,");
                                iserror=1;
                            }
                        }else {
                            expiredField.append(son.getFielddesc()+"未录入,");
                            iserror=1;
                        }
                    }
                }
                if (expiredField.length()<1){
                    value.add("资料有效期内");
                }else {
                    value.add(expiredField.toString());
                }
            }
            if (iserror==1){
                errors++;
            }
            hascolumn = 1;
            for (SolrReturnBean_Son son : fieldlist) {
                if (son.getFieldname().equalsIgnoreCase("createDate")) {
                    String timeValue = son.getFieldvalue();
                    if (timeValue != null && !timeValue.isEmpty()) {
                        timeValue = TimeUtil.getD8Date(timeValue);
                    }
                    value.add(timeValue);
                }
            }
            value.add(fieldlist.get(fieldlist.size() - 1).getFieldvalue());
            values.add(value);
        }
        if (checkExpire==1){
            colums.add("信息情况");
        }
        colums.add("更新时间");
        colums.add("已上传文件");
        zlTableVo2.setColums(colums);
        zlTableVo2.setValuelist(values);
        List<String> searchFields = SearchFieldUtils.getfield(redisTemplate, dbid);
        mv.addObject("searchList", searchFields);
        mv.addObject("errors",errors+"/"+total);
        mv.addObject("page", Integer.valueOf(page));
        mv.addObject("str", str);
        mv.addObject("ZlVo", zlTableVo2);
        mv.addObject("dbid", dbid);
        mv.addObject("dc",databaselist.getDbtitle());
        mv.addObject("dba",databaselist.getDbname());
        mv.addObject("diffValue", diffValue);
        mv.addObject("prePage", Integer.valueOf(page) - 1);
        mv.addObject("pageCount", pageCount);
        mv.addObject("count", total);
        mv.addObject("pageSize", pagesize);
        mv.setViewName("solrTable");
        mv.addObject("word", word);
        mv.addObject("perfix",perfix);
        return mv;
    }

    //文件在线预览
    @RequestMapping(value = "/fileOpen/{objid}", method = RequestMethod.GET)
    public ModelAndView fileOpen(@PathVariable String objid, HttpServletResponse response) {
        Resserver resserver = resserverService.findByServerport("6896");
        String filePath=resserver.getRespath();
        ModelAndView mv=new ModelAndView();
        Docobject docobject = docobjectService.findAllByObjectid(objid);
        String filename=docobject.getObjectfilename();
        String uid = UidUtil.getUid();
        Databaselist databaselist = databaselistService.findByDbid(Integer.valueOf(docobject.getDbid()));
        String dbaname=databaselist.getDbname();
        String tempPath = filePath + "/tempFiles/"+dbaname+"/"+uid;
        File tempFile = new File(tempPath);
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }
        File file1 = new File(filePath+"/"+dbaname+"/"+docobject.getServerfullpath());
        filename=filename.replaceAll("%","");
        String newName = tempPath + "/" + filename;
        File file2 = new File(newName);
        if (filename.endsWith(".pdf")){
            try {
                FileUtils.copyFile(file1, file2);
                String url=ip +perfix+ "/pdfjs/web/viewer.html?file="+ip+perfix+"/tempFiles/"+dbaname+"/"+uid+"/"+filename;
                mv.addObject("pdfname",docobject.getObjectfilename());
                mv.addObject("pdfurl",url);
                long length = file2.length();
                long c=10485760;
                long time = length / c;
                time=time*1000+1000;
                mv.addObject("waitTime",time);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mv.setViewName("pdfview");
            return mv;
        }else {
            InputStream is=null;
            OutputStream os=null;
            try {
                response.setContentType("image/jpeg");
                FileUtils.copyFile(file1, file2);
                response.addHeader("Content-Length", "" + file2.length());
                is=new FileInputStream(file2);
                os=response.getOutputStream();
                IOUtils.copy(is,os);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                try {
                    if (os!=null){
                        os.flush();
                        os.close();
                    }
                    if (is!=null){
                        is.close();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    throw new YunExceptions(0,"浏览图偏,关闭流bug");
                }
            }
            return null;
        }
    }

    //跳转主概览页面
    @RequestMapping(value = "/totalManager",method = RequestMethod.GET)
    public String totalManager(){
        return "totalManager";
    }



    //过期合同总数
    @RequestMapping(value = "/htCount",method = RequestMethod.GET)
    @ResponseBody
    public List<List<Object>> htCount(){
        String[] dbs={"khht","gysht","qtht"};
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        List<List<Object>> list=new ArrayList<>();
        List<Object> words=new ArrayList<>();
        List<Object> keys=new ArrayList<>();
        for (String db:dbs){
            String s = ops.get(db);
            s=s.replaceAll("\\[","");
            s=s.replaceAll("]","");
            String[] split = s.split(",");
            System.out.println("test");
            if (s.isEmpty()){
                words.add(0);
            }else {
                words.add(split.length);
            }
        }
        keys.add("客户合同");
        keys.add("供应商合同");
        keys.add("其他合同");
        list.add(keys);
        list.add(words);
        return list;
    }

    //过期合同分页查询
    @RequestMapping(value = "/htPageSearch",method = RequestMethod.POST)
    @ResponseBody
    public List<String> htPageSearch(Integer page,String dc){
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String dba=null;
        //放前端处理
//        switch (dc){
//            case "客户合同" :
//                dba="khht";
//                break;
//            case "供应商合同" :
//                dba="gysht";
//                break;
//            case "其他合同" :
//                dba="qtht";
//                break;
//        }
        String s = ops.get(dc);
        s=s.replace("[","");
        s=s.replace("]","");
        if (!s.isEmpty()){
            String[] hts = s.split(",");
            List<String> htlist=new ArrayList<>();
            List<String> list = Arrays.asList(hts);
            Integer size = list.size();
            if (size>(page*10-1)){
                list=list.subList((page-1)*10,page*10);
            }else {
                list=list.subList((page-1)*10,size);
            }
            for (String str:list){
                htlist.add(str.trim());
            }
            htlist.add(String.valueOf(size));
            return htlist;
        }
        return null;
    }

    //归档销售凭证
    @RequestMapping(value = "/xspzCount",method = RequestMethod.GET)
    @ResponseBody
    public List<List<Object>> xspzCount(){


        return null;
    }


    public static String getValue(Map<String,String> map){
        String yjName="合同名称,证照名称,发票名称,证明名称";
        for (Map.Entry<String,String> entry:map.entrySet()){
            if (yjName.contains(entry.getKey())){
                return entry.getValue();
            }
        }
        return "";
    }
}
